package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.epoch.app.otsapplicationappsdk.transferlist.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.transferlist.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.transferlist.service.TransferListService;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderdropdownselection.service.AllocateApplyOrderDropDownSelectionService;
import com.epoch.app.crunifiedinventory.dto.request.AllocateOrderDetailSearchRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderDetailVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class TransferListV2ServiceImpl implements TransferListService {

    private static Log log = Log.getLogger(TransferListV2ServiceImpl.class);

    @Resource
    UnifiedInventoryService unifiedInventoryService;

//    @Resource
//    OtsUnifiedInventoryService otsUnifiedInventoryService;
    @Resource
    CrUnifiedInventoryService otsUnifiedInventoryService;

    @Resource
    AllocateApplyOrderDropDownSelectionService allocateApplyOrderDropDownSelectionService;

    @Override
    public Object render(RenderRequest renderRequest) {
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();
        try {
            log.info("调拨单列表渲染 请求参数 {} ", JSON.toJSONString(renderRequest));
            JSONObject request = (JSONObject)JSONObject.toJSON(renderRequest.getRequestBody());
            if (request.get("currentPage") == null) {
                request.put("currentPage",1);
            }
            if (request.get("pageSize") == null) {
                request.put("pageSize",10);
            }
            //获取发货仓库
//        WmsQueryWarehouseZoneListRequest wmsQueryWarehouseZoneListRequest = new WmsQueryWarehouseZoneListRequest();
//            WmsQueryWarehouseZoneListResponse response = unifiedInventoryService.wmsQueryWarehouseZoneList(new WmsQueryWarehouseZoneListRequest());
//            log.info("调拨单列表渲染 调用库存API结果 {} ", JSON.toJSONString(response));
//            data.put("warehouseList",response.getResult());

            //单据类型
            Object  allocateApplyOrderDropDownSelection = allocateApplyOrderDropDownSelectionService.queryDocumentType();
            log.info("调拨预报单创建渲染 调拨类型 {} ",JSONObject.toJSONString(allocateApplyOrderDropDownSelection));
            JSONObject allocateApplyOrderDropDownSelectionJson = (JSONObject)JSONObject.toJSON(allocateApplyOrderDropDownSelection);
            data.put("allocationType",allocateApplyOrderDropDownSelectionJson.getJSONArray("result"));


            Result<List<AllocateOrderDetailVO>> allocateOrderListResult =  renderData(request);
            if (allocateOrderListResult.isSuccess()) {
                data.put("list",allocateOrderListResult.getResult());
            }
            if (request.get("page") == null || request.getInteger("page") <= 1) {
                data.put("reload",true);
            } else {
                data.put("reload",false);
            }
            data.put("applyCode",request.getString("applyCode"));
            data.put("currentPage",request.getInteger("currentPage"));
            data.put("pageSize",request.getInteger("pageSize"));
            data.put("totalPage",Math.ceil((double) allocateOrderListResult.getTotal()/(double)request.getInteger("pageSize")));
            result.put("success",true);
            result.put("result",data);
        } catch (Exception e) {
            log.info("调拨单列表渲染异常 {}", e.getMessage());
            result.put("success",false);
            result.put("message","调拨单列表渲染异常");
        }
        return result;
    }


    @Override
    public Object async(AsyncRequest asyncRequest) {
        JSONObject result = new JSONObject();
        try {
            log.info("调拨单列表异步渲染 请求参数 {} ", JSON.toJSONString(asyncRequest));
            JSONObject request = (JSONObject)JSONObject.toJSON(asyncRequest.getRequestBody());

            JSONObject updateFields = new JSONObject();
            if (request != null) {
                if (request.get("fields") != null) {
                    JSONObject fieldsJson = request.getJSONObject("fields");
                    updateFields = fieldsJson.getJSONObject("updateFields");
                }
            }
            if (updateFields.get("currentPage") == null) {
                updateFields.put("currentPage",1);
            }
            if (updateFields.get("pageSize") == null) {
                updateFields.put("pageSize",10);
            }
            Result<List<AllocateOrderDetailVO>> callApiResult = renderData(updateFields);
            log.info("调拨单列表异步渲染 调拨单接口出参 {} ", JSON.toJSONString(callApiResult));
            JSONObject data = new JSONObject();
            if (updateFields.get("currentPage") == null || updateFields.getInteger("currentPage") <= 1) {
                data.put("reload",true);
            } else {
                data.put("reload",false);
            }

            //单据类型
            Object  allocateApplyOrderDropDownSelection = allocateApplyOrderDropDownSelectionService.queryDocumentType();
            log.info("调拨单列表异步 调拨类型 {} ",JSONObject.toJSONString(allocateApplyOrderDropDownSelection));
            JSONObject allocateApplyOrderDropDownSelectionJson = (JSONObject)JSONObject.toJSON(allocateApplyOrderDropDownSelection);
            data.put("allocationType",allocateApplyOrderDropDownSelectionJson.getJSONArray("result"));

            data.put("updateFields",updateFields);
            data.put("list",callApiResult.getResult());
            data.put("currentPage",updateFields.getInteger("currentPage"));
            data.put("pageSize",updateFields.getInteger("pageSize"));
            data.put("totalPage",Math.ceil((double) callApiResult.getTotal()/(double)updateFields.getInteger("pageSize")));
            result.put("success",true);
            result.put("result",data);
        } catch (Exception e) {
            log.info("调拨单列表异步渲染异常 {}", e.getMessage());
            result.put("success",false);
            result.put("message","调拨单列表异步渲染异常");
        }
        log.info("调拨单列表异步 出参 {} ", JSON.toJSONString(result));
        return result;
    }

    public Result<List<AllocateOrderDetailVO>> renderData(JSONObject request) {
        if (request == null) {
            return new Result();
        }

        AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest = new AllocateOrderDetailSearchRequest();
        Integer page = request.getInteger("currentPage");
        Integer size = request.getInteger("pageSize");
        Integer start=(page-1)*size;

        allocateOrderDetailSearchRequest.setStart(start);
        allocateOrderDetailSearchRequest.setLimit(size);
        if (request.get("code") != null && !"".equals(request.getString("code"))) {
            allocateOrderDetailSearchRequest.setCode(request.getString("code"));
        }
        if (request.get("applyCode") != null && !"".equals(request.getString("applyCode"))) {
            allocateOrderDetailSearchRequest.setAllocateApplyOrderCode(request.getString("applyCode"));
        }
        if (request.get("shipWarehouseId") != null && !"".equals(request.getString("shipWarehouseId"))) {
            allocateOrderDetailSearchRequest.setShipAreaId(request.getString("shipWarehouseId"));
        }

        if (request.get("scItemCode") != null && !"".equals(request.getString("scItemCode"))) {
            allocateOrderDetailSearchRequest.setScItemCode(request.getString("scItemCode"));
        }

        if (request.get("startTime") != null && !"".equals(request.get("startTime"))) {
//            allocateOrderDetailSearchRequest.setDocDateBeginLong(request.getLong("startTime"));
            allocateOrderDetailSearchRequest.setCreateTimeBeginLong(request.getLong("startTime"));
        }
        if (request.get("endTime") != null && !"".equals(request.get("endTime"))) {
//            allocateOrderDetailSearchRequest.setDocDateEndLong(request.getLong("endTime"));
            allocateOrderDetailSearchRequest.setCreateTimeEndLong(request.getLong("endTime"));
        }
        if (request.get("tagList") != null) {
            JSONArray tagListJson = request.getJSONArray("tagList");
            if (CollectionUtils.isNotEmpty(tagListJson)) {
                List<String> tagList = new ArrayList<>();
                for (Object obj : tagListJson) {
                    tagList.add(obj.toString());
                }
                allocateOrderDetailSearchRequest.setTypeList(tagList);
            }
        }
        log.info("调拨单列表渲染 调用调拨单API入参 {} ", JSON.toJSONString(allocateOrderDetailSearchRequest));
        Result<List<AllocateOrderDetailVO>> allocateOrderDetailVO = otsUnifiedInventoryService.allocateOrderSearch(allocateOrderDetailSearchRequest);
        log.info("调拨单列表渲染 调用调拨单API结果 {} ", JSON.toJSONString(allocateOrderDetailVO));
        return allocateOrderDetailVO;
    }

}
